var express = require("express");
var router = express.Router();
const user = require("../sql/user");
const registerpasswords = require("../sql/registerpassword");


// 注册的第一步   命中/register的时候 要渲染注册页面 
router.get('/',function(req,res,next){
    console.log('进来了注册的第一步')
    res.render('register')
})

// 注册的第二步调用数据库  <form action="/register/in" method="post">
router.post('/in',function(req,res,next){
    const obj = req.body;
    user.findOne({username:obj.username},(err,data)=>{
        if(err){
            console.log(err);
        }
        if(data){
            res.render('register2')
        }else{
            registerpasswords.findOne({code:obj.code},(err,data)=>{
                if(err){
                    console.log(err);
                }
                if(data){
                    registerpasswords.deleteMany({code:obj.code},(err,data)=>{
                        if(err){
                            console.log(err);
                        }
                        console.log('删除成功');  
                    });
                    user.insertMany({username:obj.username,password:obj.password},(err)=>{
                        if(err){
                            console.log(err);
                        }
                        console.log('添加数据成功');
                    })
                    res.render('login')
                }else{
                    res.render('register2')      
                }
            })
        }
    })
})
module.exports = router;